﻿#include "widget.h"
#include "ui_widget.h"

#include <QMouseEvent>
#include <QDebug>
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QMessageBox>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QPainter>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    //this->setFont(QFont("Arial",15));
    //this->setFont(QFont("微软雅黑",15));
    //this->setStyleSheet("QWidget { font-family: 微软雅黑;}");
    setFixedSize(600,922);
    setWindowFlag(Qt::FramelessWindowHint);

    //新建一个菜单组件
    menuQuit = new QMenu(this);
    //设置菜单文字颜色
    menuQuit->setStyleSheet("QMenu{background-color:white;}");
    //新建菜单动作
    QAction *openAct = new QAction(QIcon(":/icon/close.png"),tr("退出"),this);
    //添加菜单动作
    menuQuit->addAction(openAct);
    //设置点击菜单动作触发
    connect(menuQuit,&QMenu::triggered,this,[=](){
        this->close();
    });

    //QHttp
    manager = new QNetworkAccessManager(this);

    strUrl = "http://gfeljm.tianqiapi.com/api?unescape=1&version=v9&appid=24447778&appsecret=HeJ9m3CJ";
    QUrl urlTianQi(strUrl);
    QNetworkRequest res(urlTianQi);
    reply = manager->get(res);
    //网络请求后读取数据
    connect(manager,&QNetworkAccessManager::finished,this,&Widget::readHttpRply);

    //初始化数组 QList重写了<<
    mWeekList << ui->label0401_week << ui->label0402_week
              << ui->label0403_week << ui->label0404_week
              << ui->label0405_week << ui->label0406_week;

    mDateList << ui->label0401_date << ui->label0402_date
              << ui->label0403_date << ui->label0404_date
              << ui->label0405_date << ui->label0406_date;

    mIconList << ui->label0401_weatherIcon << ui->label0402_weatherIcon
              << ui->label0403_weatherIcon << ui->label0404_weatherIcon
              << ui->label0405_weatherIcon << ui->label0406_weatherIcon;

    mWeaTypeList << ui->label0401_weatherType << ui->label0402_weatherType
                 << ui->label0403_weatherType << ui->label0404_weatherType
                 << ui->label0405_weatherType << ui->label0406_weatherType;

    mAirqList << ui->label0401_airQt << ui->label0402_airQt
              << ui->label0403_airQt << ui->label0404_airQt
              << ui->label0405_airQt << ui->label0406_airQt;

    mFxList << ui->label0401_windType << ui->label0402_windType
            << ui->label0403_windType << ui->label0404_windType
            << ui->label0405_windType << ui->label0406_windType;

    mFlList << ui->label0401_windLevel << ui->label0402_windLevel
            << ui->label0403_windLevel << ui->label0404_windLevel
            << ui->label0405_windLevel << ui->label0406_windLevel;

    //根据keys,设置icon的路径
    mTypeMap.insert("暴雪",":/icon/type/BaoXue.png");
    mTypeMap.insert("暴雨",":/icon/type/BaoYu. png");
    mTypeMap.insert("暴雨到大暴雨",":/icon/type/BaoYuDaoDaBaoYu.png");
    mTypeMap.insert("大暴雨",":/icon/type/DaBaoYu.png");
    mTypeMap.insert("大暴雨到特大暴雨",":/icon/type/DaBaoYuDaoTeDaBaoYu.png");
    mTypeMap.insert("大到暴雪",":/icon/type/DaDaoBaoXue.png");
    mTypeMap.insert("大雪",":/icon/type/DaXue.png");
    mTypeMap.insert("大雨",":/icon/type/DaYu.png");
    mTypeMap.insert("冻雨",":/icon/type/DongYu.png");
    mTypeMap.insert("多云",":/icon/type/DuoYun.png");
    mTypeMap.insert("浮沉",":/icon/type/FuChen.png");
    mTypeMap.insert("雷阵雨",":/icon/type/LeiZhenYu.png");
    mTypeMap.insert("雷阵雨伴有冰雹",":/icon/type/LeiZhenYuBanYouBingBao.png");
    mTypeMap.insert("霾",":/icon/type/Mai.png");
    mTypeMap.insert("强沙尘暴",":/icon/type/QiangShaChenBao.png");
    mTypeMap.insert("晴",":/icon/type/Qing.png");
    mTypeMap.insert("沙尘暴",":/icon/type/ShaChenBao.png");
    mTypeMap.insert("特大暴雨",":/icon/type/TeDaBaoYu.png");
    mTypeMap.insert("undefined",":/icon/type/undefined.png");
    mTypeMap.insert("雾",":/icon/type/Wu.png");
    mTypeMap.insert("小到中雪",":/icon/type/XiaoDaoZhongXue.png");
    mTypeMap.insert("小到中雨",":/icon/type/XiaoDaoZhongYu.png");
    mTypeMap.insert("小雪",":/icon/type/XiaoXue.png");
    mTypeMap.insert("小雨",":/icon/type/XiaoYu.png");
    mTypeMap.insert("雪",":/icon/type/Xue.png");
    mTypeMap.insert("扬沙",":/icon/type/YangSha.png");
    mTypeMap.insert("阴",":/icon/type/Yin.png");
    mTypeMap.insert("雨",":/icon/type/Yu.png");
    mTypeMap.insert("雨夹雪",":/icon/type/YuJiaXue.png");
    mTypeMap.insert("阵雪",":/icon/type/ZhenXue.png");
    mTypeMap.insert("阵雨",":/icon/type/ZhenYu.png");
    mTypeMap.insert("中到大雪",":/icon/type/ZhongDaoDaXue.png");
    mTypeMap.insert("中到大雨",":/icon/type/ZhongDaoDaYu.png");
    mTypeMap.insert("中雪",":/icon/type/ZhongXue.png");
    mTypeMap.insert("中雨",":/icon/type/ZhongYu.png");

    ui->widget_hightWen->installEventFilter(this);//安装事件过滤器
    ui->widget_lowWen->installEventFilter(this);

}

Widget::~Widget()
{
    delete ui;
}


//获取窗口偏移值
void Widget::mousePressEvent(QMouseEvent *event)
{
    if(event->button() == Qt::RightButton){
        //qDebug() << "right Mouse clicked!";
        menuQuit->exec(QCursor::pos());
    }
    //鼠标当前位置event->globalPos()
    //窗口当前位置this->pos()
    //窗口新位置 event->globalPos() - mOffset
    //移动思路：当鼠标按下获得鼠标当前位置与窗口左上角的位置，计算出偏移值，然后当我们按住鼠标可以根据这个偏移值去改变窗口位置
    if(event->button() == Qt::LeftButton){
        //qDebug() << "right Mouse clicked!";
        mOffset = event->globalPos() - this->pos();
    }
}


//拖动窗口
void Widget::mouseMoveEvent(QMouseEvent *event)
{
    this->move(event->globalPos() - mOffset);
}

//画图，检测画图事件
bool Widget::eventFilter(QObject *watched, QEvent *event)
{
    if(watched == ui->widget_hightWen && event->type() == QEvent::Paint){
        drawTempLineHigh();
        return true;//表示事件已被处理
    }
    if(watched == ui->widget_lowWen && event->type() == QEvent::Paint){
         drawTempLineLow();
         return true;//表示事件已被处理
    }
    return QWidget::eventFilter(watched, event);
}


//将获取到的jison文件数据转换为json对象 类型
void Widget::parseWeatherJsonData(QByteArray rawData)
{
    QJsonDocument jsonObj = QJsonDocument::fromJson(rawData);
    if(!jsonObj.isNull() && jsonObj.isObject()){
        QJsonObject objRoot = jsonObj.object();


    }
}

//将获取到的jison文件数据转换为json对象 类型
//并进行处理
void Widget::parseWeatherJsonDataNew(QByteArray rawData)
{
    QJsonDocument jsonDoc = QJsonDocument::fromJson(rawData);
    if( !jsonDoc.isNull() && jsonDoc.isObject()){
        //先做03部分的初始化，json文件转换成json对象(键值对)，再转换成json数组
        QJsonObject jsonRoot = jsonDoc.object();
        days[0].mCity = jsonRoot["city"].toString();
        days[0].mPm25 = jsonRoot["aqi"].toObject()["pm25"].toString();
        if( jsonRoot.contains("data") && jsonRoot["data"].isArray()){
            //转成json数组，数组中存储的是键值对
            QJsonArray weaArray = jsonRoot["data"].toArray();
            for(int i = 0; i < weaArray.size(); i++){//循环遍历
                QJsonObject obj = weaArray[i].toObject();
                //qDebug() << obj["date"].toString() << obj["wea"].toString();
                //数组中的一个个数据添加到天数对象中(里面有每天的气温、天气情况等数据)
                days[i].mDate = obj["date"].toString();
                days[i].mWeek = obj["week"].toString();
                days[i].mWeathType = obj["wea"].toString();
                days[i].mTemp = obj["tem"].toString();
                days[i].mTempLow = obj["tem2"].toString();
                days[i].mTempHigh = obj["tem1"].toString();
                days[i].mFx = obj["win"].toArray()[0].toString();
                days[i].mFl = obj["win_speed"].toString();
                days[i].mAirq = obj["air_level"].toString();
                days[i].mTips = obj["air_tips"].toString();
                days[i].mHu = obj["humidity"].toString();

            }
        }
    }
    updateUI();
}

void Widget::updateUI()
{
    QPixmap pixmap;

    //解析日期

    ui->label01_date->setText(days[0].mDate+"  "+days[0].mWeek);

    //解析城市名称
    //QString cityName = objRoot["city"].toString();
    ui->label02_city->setText(days[0].mCity+"市");

    //解析当前温度
    //QString currentTemp = objRoot["tem"].toString();
    ui->label02_currwendu->setText(days[0].mTemp+"℃");
    ui->label02_fangwei->setText(days[0].mTempLow+"℃"+"～"
            +days[0].mTempHigh+"℃");

    //解析天气类型
    ui->label02_weather->setText(days[0].mWeathType);
    ui->label02_weatherIcon->setPixmap(mTypeMap[days[0].mWeathType]);

    //感冒指数
    ui->label03_ganMao->setText(days[0].mTips);
    //风向
    ui->label03_windType->setText(days[0].mFx);
    //风力
    ui->label03_windLevel->setText(days[0].mFl);
    //PM2.5
    ui->label03_PMvalue->setText(days[0].mPm25);
    //湿度
    ui->label03_wetValue->setText(days[0].mHu);
    //空气质量
    ui->label03_airValue->setText(days[0].mAirq);

    ui->label0401_weatherType->setText(days[0].mWeathType);

    ui->label0404_weatherType->setText(days[3].mWeathType);

    for(int i = 0; i < 6; i++){

//设置日期
        mWeekList[i]->setText(days[i].mWeek);
        mWeekList[0]->setText("今天");
        mWeekList[1]->setText("明天");
        mWeekList[2]->setText("后天");
        QStringList dayList = days[i].mDate.split("-");
        mDateList[i]->setText(dayList.at(1)+"-"+dayList.at(2));//2024-01-24
//设置天气
        //缩放图片大小和label大小能匹配
        int index = days[i].mWeathType.indexOf("转");//找到字符串中第几个字符出现了“转”，返回出现位置

        //如果是正值，说明字符带“转”
        if(index != -1){
            pixmap = mTypeMap[days[i].mWeathType.left(index)];//截取左边长index的days[i].mWeathType，返回第一个天气
        }else{
            pixmap = mTypeMap[days[i].mWeathType];
        }
        pixmap = pixmap.scaled(mIconList[i]->size(),Qt::KeepAspectRatio,Qt::SmoothTransformation);
        mIconList[i]->setMaximumHeight(50);
        mIconList[i]->setMaximumWidth(ui->widget02->width()/6.5);
        mIconList[i]->setPixmap(pixmap);
        mWeaTypeList[i]->setText(days[i].mWeathType);
//设置优良
        QString airQ = days[i].mAirq;
        mAirqList[i]->setText(airQ);
        if( airQ == "优"){
             mAirqList[i]->setStyleSheet("background-color: rgb(150, 213, 32); border-radius: 7px");
        }
        if( airQ == "良"){
             mAirqList[i]->setStyleSheet("background-color: rgb(208, 107, 39); border-radius: 7px;");
        }
        if( airQ == "轻度"){
             mAirqList[i]->setStyleSheet("background-color: rgb(255, 199, 199); border-radius: 7px;");
        }
        if( airQ == "中度"){
             mAirqList[i]->setStyleSheet("background-color: rgb(255, 17, 17); border-radius: 7px;");
        }
        if( airQ == "重度"){
             mAirqList[i]->setStyleSheet("background-color: rgb(153, 0, 0); border-radius: 7px; ");
        }


//设置风
        mFxList[i]->setText(days[i].mFx);
        index = days[i].mFl.indexOf("转");
        if(index != -1){
            mFlList[i]->setText(days[i].mFl.left(index));
        }else{
            mFlList[i]->setText(days[i].mFl);
        }

    }
    update();//设置完UI之后一定要调用这个去重新显示ui变化
}

void Widget::readHttpRply(QNetworkReply *reply)
{
    int resCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
    qDebug() << resCode;
    if(reply->error() == QNetworkReply::NoError && resCode == 200){
        QByteArray data =  reply->readAll();
        //parseWeatherJsonData(data);
        parseWeatherJsonDataNew(data);
        //qDebug() << QString::fromUtf8(data);
    }else{
        QMessageBox mes;
        mes.setWindowTitle("错误");
        mes.setText("网络请求失败");
        mes.setStyleSheet("QPushButton {color:red}");
        mes.setStandardButtons(QMessageBox::Ok);
        mes.exec();
    }

}


void Widget::drawTempLineHigh()
{

    QPainter painter(ui->widget_hightWen);
    painter.setRenderHint(QPainter::Antialiasing,true);
    painter.setBrush(Qt::yellow);
    painter.setPen(Qt::yellow);

    int ave;
    int sum = 0;
    int offSet = 0;
    int middle = ui->widget_hightWen->height()*0.7;
    qDebug() << ui->widget_hightWen->height();
    for(int i = 0; i < 6; i++){
        //qDebug() << "i:" <<days[i].mTempHigh.toInt();
        sum += days[i].mTempHigh.toInt();
    }
    ave = sum / 6;
    //qDebug() << "sum:" <<sum;
    //定义出6个点
    QPoint points[6];
    for(int i = 0; i < 6; i++){
        points[i].setX(mAirqList[i]->x() + mAirqList[i]->width()/2);//x()是widget父类的方法，获取到当前label的一个X值，然后再加上label的中间值
        offSet = (days[i].mTempHigh.toInt() - ave)*3; //偏移量，让点偏移一点，显示的数据减去平均温度
        points[i].setY(middle-offSet);//label的一半减去偏移的量
        //画出6个点
        painter.drawEllipse(QPoint(points[i]),3,3);
        //画出当天温度
        painter.drawText(points[i].x()-15,points[i].y()-15,days[i].mTempHigh+"°");
    }

    for(int i = 0; i < 5; i++){
         painter.drawLine(points[i],points[i+1]);
    }


}

void Widget::drawTempLineLow()
{
    QPainter painter(ui->widget_lowWen);
    painter.setRenderHint(QPainter::Antialiasing,true);
    painter.setBrush(QColor(0, 170, 171));
    painter.setPen(QColor(0, 255, 255));

    int ave;
    int sum = 0;
    int offSet = 0;
    int middle = ui->widget_lowWen->height()*0.7;
    for(int i = 0; i < 6; i++){
        //qDebug() << "i:" <<days[i].mTempHigh.toInt();
        sum += days[i].mTempLow.toInt();
    }
    ave = sum / 6;
    //qDebug() << "sum:" <<sum;
    //定义出6个点
    QPoint points[6];
    for(int i = 0; i < 6; i++){
        points[i].setX(mAirqList[i]->x() + mAirqList[i]->width()/2);
        offSet = (days[i].mTempLow.toInt() - ave)*3;
        points[i].setY(middle - offSet);
        //画出6个点
        painter.drawEllipse(QPoint(points[i]),3,3);
        //画出当天温度
        painter.drawText(points[i].x()-15,points[i].y()-15,days[i].mTempLow+"°");
    }

    for(int i = 0; i < 5; i++){
         painter.drawLine(points[i],points[i+1]);
    }

}

void Widget::on_pushButton01_find_clicked()
{

    QString cityNameFromUser = ui->lineEdit01_findText->text();
    QString cityCode = citycodeutils.getCityCodeFromName(cityNameFromUser);
    qDebug() << cityCode;
    if(cityCode != NULL){
        strUrl += "&cityid=" + cityCode;
        manager->get(QNetworkRequest(QUrl(strUrl)));
    }else{
        QMessageBox mes;
        mes.setWindowTitle("错误");
        mes.setText("请输入正确的城市名称！");
        mes.setStyleSheet("QPushButton {color:red}");
        mes.setStandardButtons(QMessageBox::Ok);
        mes.exec();
    }
}

void Widget::on_lineEdit01_findText_returnPressed()
{
    on_pushButton01_find_clicked();
}
